package com.wr.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.wr.mapper.CommentMapper;
import com.wr.model.Comment;
import com.wr.service.CommentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author weirong
 * @Title:
 * @Description:
 * @date 2018/6/1315:30
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    private String BLOG_COMMENT_CACHE_KEY = "blog:comment:cache:";

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return commentMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insertSelective(Comment record) {
        Set<String> keys = redisTemplate.keys(BLOG_COMMENT_CACHE_KEY + "*");
        redisTemplate.delete(keys);
        return commentMapper.insertSelective(record);
    }

    @Override
    public Comment selectByPrimaryKey(Integer id) {
        return commentMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Comment record) {
        return commentMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public JSONObject listByArtId(Integer artid, Integer pageNo, Integer pageSize) {
        JSONObject comments = new JSONObject();
        String key = BLOG_COMMENT_CACHE_KEY + artid+"pageNo:"+pageNo;
        Object o = redisTemplate.opsForValue().get(key);
        String reusltJson = null;
        if(o != null) {
            reusltJson = String.valueOf(o);
            comments = JSONObject.parseObject(reusltJson);
            return comments;
        }
        PageHelper.startPage(pageNo,pageSize);
        List<Comment> comments1 = commentMapper.listByArtId(artid);
        //用PageInfo对结果进行包装
        PageInfo<Comment> page = new PageInfo<Comment>(comments1);

        comments.put("total",page.getTotal());
        comments.put("rows", JSONArray.parseArray(JSON.toJSONString(comments1)));

        redisTemplate.opsForValue().set(key,comments.toJSONString(),5, TimeUnit.HOURS);
        return comments;
    }
}
